package org.wsff.tools.api.gateway.impl.spring;

import java.lang.reflect.Field;

import org.springframework.aop.framework.AdvisedSupport;
import org.springframework.aop.support.AopUtils;

/**
 * AopTargetUtils
 * @author ryan
 * @version Id: AopTargetUtils.java, v 0.1 2022-01-19 18:51 ryan Exp $$
 */
public class AopTargetUtils {
    private static final String CGLIB_FIELD   = "CGLIB$CALLBACK_0";
    private static final String ADVISED_FIELD = "advised";
    private static final String H_FIELD       = "h";

    /**
     * 获取目标对象
     *
     * @param proxy 代理
     * @return 代理对象
     */
    public static Object getTarget(Object proxy) {

        if (!AopUtils.isAopProxy(proxy)) {
            return proxy;//不是代理对象  
        }

        if (AopUtils.isJdkDynamicProxy(proxy)) {
            return getJdkDynamicProxyTargetObject(proxy);
        } else { //cglib  
            return getCglibProxyTargetObject(proxy);
        }

    }

    /**
     * 获取cglib代理对象
     *
     * @param proxy 代理
     * @return 代理对象
     */
    private static Object getCglibProxyTargetObject(Object proxy) {
        try {
            Field h = proxy.getClass().getDeclaredField(CGLIB_FIELD);
            h.setAccessible(true);
            Object _proxy = h.get(proxy);

            Field advised = _proxy.getClass().getDeclaredField(ADVISED_FIELD);
            advised.setAccessible(true);

            return ((AdvisedSupport) advised.get(_proxy)).getTargetSource().getTarget();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取JDK动态代理对象
     *
     * @param proxy 代理
     * @return 代理对象
     */
    private static Object getJdkDynamicProxyTargetObject(Object proxy) {
        try {
            Field h = proxy.getClass().getSuperclass().getDeclaredField(H_FIELD);
            h.setAccessible(true);
            Object _proxy = h.get(proxy);

            Field advised = _proxy.getClass().getDeclaredField(ADVISED_FIELD);
            advised.setAccessible(true);

            return ((AdvisedSupport) advised.get(_proxy)).getTargetSource().getTarget();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
